//
//  OrderDetailViewController.m
//  DanaKreditLoan
//
//  Created by ZhengChengFeng on 2024/10/21.
//

#import "OrderDetailViewController.h"
#import "OrderDetailModel.h"
#import "IdCardVertifyModel.h"

#import "OrderDetBannerView.h"

#import "IdCardViewController.h"
#import "IdCardFaceViewController.h"
#import "IdCardSuccessViewController.h"

#import "PersonInfoViewController.h"
#import "ContactInfoViewController.h"
#import "BankCardInfoViewController.h"

#define kDefaultFixHeight (IS_IPhoneX_All ? kHeight_BottomSafe : 20)

@interface OrderDetailViewController ()<CLLocationManagerDelegate>

@property (nonatomic) UIView *tabHeadView;
@property (nonatomic) UIImageView *midImgV;

@property (nonatomic) BOOL isOffsetY;

@property (nonatomic) OrderDetailModel *model;



@property (nonatomic) CLLocationManager *locationManager;
@property (nonatomic) NSTimer *timer;
@property (nonatomic) NSInteger timeInt;
@property (nonatomic) BOOL isLocationSuccess;
@property (nonatomic) NSString *startTimeStr,*endTimeStr;

@end

@implementation OrderDetailViewController

- (void)loadCityData{
    NSMutableDictionary *muDic = @{
        @"guided":@"guidedAddress",
        @"revenge":@"revengeAddress",
    }.mutableCopy;
    [HttpNetHelper getNetworkHelperForPath:kCityAddressUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            return;
        }
        
        NSDictionary *dic = responseDic[@"clip"];
       
        NSArray *vanityAry = dic[@"continuing"];
        
        if (isArray(vanityAry)) {
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:kCityDataAry];
            
            [[NSUserDefaults standardUserDefaults] setValue:vanityAry forKey:kCityDataAry];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        
    } onCompleteFailur:^(NSError * _Nonnull error) {
        
    } withIsForm:NO];
    
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [self loadData];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}

- (void)loadData{
    NSMutableDictionary *muDic = @{
        @"largely":esString(self.idStr),
        @"mainland":@"mainlandOrderDet",
    }.mutableCopy;
    [BoxLoadingHelper showBoxLoadingWithMessage:@""];
    [HttpNetHelper postNetworkHelperForPath:kOrderDetailUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        [BoxLoadingHelper hideBoxLoading];
        [BoxLoadingHelper hideBoxLoadingFromView:self.view];
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            [self initHeadDataView];
            [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
            return;
        }
        
        [self.data removeAllObjects];
        
        
        NSDictionary *dic = responseDic[@"clip"];
        
        OrderDetailModel *model = [OrderDetailModel mj_objectWithKeyValues:dic];
        self.model = model;
        
        
        [self initHeadDataView];
        [self initMidImgData];
        [self initBannerView];
        [self initFootView];

        
    } onCompleteFailur:^(NSError * _Nonnull error) {
        [self initHeadDataView];
        [BoxLoadingHelper hideBoxLoading];
        [BoxLoadingHelper hideBoxLoadingFromView:self.view];
    } withIsForm:YES];
   
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self loadCityData];
}

- (void)initHeadDataView{
    UIView *tabHeadView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, DimensionBaseIphone6(144+640)+kDefaultFixHeight)];
    self.tableView.tableHeaderView = tabHeadView;
    self.tabHeadView = tabHeadView;
    
    UIImageView *topImgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, DimensionBaseIphone6(200))];
    topImgV.image = [UIImage imageNamed:@"icon_orderDet1"];
    [tabHeadView addSubview:topImgV];
    
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, DimensionBaseIphone6(54), 35, 35)];
    [backBtn setImage:[UIImage imageNamed:@"icon_orderDet2"] forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"icon_orderDet2"] forState:UIControlStateSelected];
    [backBtn setImage:[UIImage imageNamed:@"icon_orderDet2"] forState:UIControlStateHighlighted];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [tabHeadView addSubview:backBtn];
    
    UIView *backV = [[UIView alloc] initWithFrame:CGRectMake(0, DimensionBaseIphone6(164), kScreenWidth, DimensionBaseIphone6(640) + kDefaultFixHeight)];
    backV.backgroundColor = kTableViewBackColor;
    [tabHeadView addSubview:backV];
    backV.layer.mask = [NSString UIBezierPathWithRect:backV.bounds withCorners:UIRectCornerTopLeft|UIRectCornerTopRight withRadiu:CGSizeMake(14, 14)];
    
    UIImageView *midImgV = [[UIImageView alloc] initWithFrame:CGRectMake(15, 0, kScreenWidth - 30, DimensionBaseIphone6(350))];
    midImgV.image = [UIImage imageNamed:@"icon_orderDet3"];
    [tabHeadView addSubview:midImgV];
    self.midImgV = midImgV;

}

- (void)initMidImgData{
    UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(20, DimensionBaseIphone6(140), DimensionBaseIphone6(28), DimensionBaseIphone6(28))];
    icon.image = [UIImage imageNamed:@"icon_home4"];
    [self.midImgV addSubview:icon];
    
    UILabel *nameLab = [UILabel  createLabel:[UIFont fontWithName:kFutura size:16] color:kBlackColor];
    [self.midImgV addSubview:nameLab];
    nameLab.frame = CGRectMake(icon.right + 3, 0, 200, 25);
    nameLab.centerY = icon.centerY;
    nameLab.text = esString(self.model.refugees.caulfeild);
    
    UIImageView *icon2 = [[UIImageView alloc] initWithFrame:CGRectMake(self.midImgV.width - 18 - 78, DimensionBaseIphone6(97), 78, DimensionBaseIphone6(164))];
    icon2.image = [UIImage imageNamed:@"icon_home3"];
    [self.midImgV addSubview:icon2];
    
    UILabel *priceLab = [UILabel createLabel:[UIFont fontWithName:kFuturaBold size:44] color:kButtonDefaultColor];
    priceLab.frame = CGRectMake(20, icon.bottom + DimensionBaseIphone6(18), self.midImgV.width - 20 - 20, DimensionBaseIphone6(44));
    [self.midImgV addSubview:priceLab];
    priceLab.text = esString(self.model.refugees.founders);
    
    UILabel *priceLabDesc = [UILabel createLabel:[UIFont fontWithName:kFutura size:14] color:kBlackColor];
    priceLabDesc.frame = CGRectMake(20, priceLab.bottom + DimensionBaseIphone6(10), self.midImgV.width - 20 - 20 - 74 - 10, DimensionBaseIphone6(15));
    [self.midImgV addSubview:priceLabDesc];
    priceLabDesc.text = esString(self.model.refugees.kaloka);
    
    UILabel *rateLab = [UILabel createLabel:[UIFont fontWithName:kFutura size:15] color:[UIColor colorWithHexString:@"#FFFFFF"]];
    rateLab.frame = CGRectMake(20, priceLabDesc.bottom + DimensionBaseIphone6(30), 160, DimensionBaseIphone6(18));
    [self.midImgV addSubview:rateLab];
    rateLab.text = esString(self.model.refugees.mangrove.california.defy);
    
    UILabel *rateLabDesc = [UILabel createLabel:[UIFont fontWithName:kFutura size:13] color:[UIColor colorWithHexString:@"#75FA8D"]];
    rateLabDesc.frame = CGRectMake(20, rateLab.bottom + DimensionBaseIphone6(5), 160, DimensionBaseIphone6(16));
    [self.midImgV addSubview:rateLabDesc];
    rateLabDesc.text =esString(self.model.refugees.mangrove.california.arrow);
    
    UILabel *termLab = [UILabel createLabel:[UIFont fontWithName:kFutura size:15] color:[UIColor colorWithHexString:@"#FFFFFF"]];
    termLab.frame = CGRectMake(rateLab.right + 10, rateLab.top, 160, DimensionBaseIphone6(18));
    [self.midImgV addSubview:termLab];
    termLab.text = esString(self.model.refugees.weakness);
    
    UILabel *termLabDesc = [UILabel createLabel:[UIFont fontWithName:kFutura size:13] color:[UIColor colorWithHexString:@"#75FA8D"]];
    termLabDesc.frame = CGRectMake(termLab.left, rateLabDesc.top, 160, DimensionBaseIphone6(16));
    [self.midImgV addSubview:termLabDesc];
    termLabDesc.text = esString(self.model.refugees.wider);
    
}

- (void)initBannerView{
    NSArray *arr = self.model.peroxide;
    OrderDetBannerView *bannerView = [[OrderDetBannerView alloc] initWithFrame:CGRectMake(0, self.midImgV.bottom, kScreenWidth, DimensionBaseIphone6(328+20+30)) withDataAry:arr];
    [self.tabHeadView addSubview:bannerView];
    
    bannerView.callBackTapNum = ^(NSInteger num) {
        
        
        PeroxideModel *mod = [PeroxideModel mj_objectWithKeyValues:arr[num]];
        if ([mod.undiluted isEqualToString:kIdCardInfoVertify]) {
            [self goIdCardVertify:esString(mod.arrow)];
        }
        else if ([mod.undiluted isEqualToString:kPersonInfoVertify]) {
            if ([mod.keller integerValue] == 1) {
                [self goPersonalInfoVertify:esString(mod.arrow)];
            } else {
                [self clickStartBorrowing];
            }
        }
        else if ([mod.undiluted isEqualToString:kContactInfoVertify]) {
            if ([mod.keller integerValue] == 1) {
                [self goEmergencyInfoVertify:esString(mod.arrow)];
            } else {
                [self clickStartBorrowing];
            }
        }
        else if ([mod.undiluted isEqualToString:kBankInfoVertify]) {
            if ([mod.keller integerValue] == 1) {
                [self goBankCardVertify:esString(mod.arrow)];
            } else {
                [self clickStartBorrowing];
            }
        }
        
    };
    
}

- (void)initFootView{

    UIButton *footBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, self.tabHeadView.height - kDefaultFixHeight  - DimensionBaseIphone6(48), kScreenWidth - 30 , DimensionBaseIphone6(48))];
    footBtn.titleLabel.font = [UIFont fontWithName:kFuturaMedium size:15];
    [footBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [footBtn setTitleColor:kWhiteColor forState:UIControlStateSelected];
    [footBtn setTitleColor:kWhiteColor forState:UIControlStateHighlighted];
    [footBtn setTitle:ASLocalizedString(@"Start Borrowing") forState:UIControlStateNormal];
    [footBtn setTitle:ASLocalizedString(@"Start Borrowing") forState:UIControlStateSelected];
    [footBtn setTitle:ASLocalizedString(@"Start Borrowing") forState:UIControlStateHighlighted];
    [footBtn setImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateNormal];
    [footBtn setImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateSelected];
    [footBtn setImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateHighlighted];
    [footBtn addTarget:self action:@selector(clickStartBorrowing) forControlEvents:UIControlEventTouchUpInside];
    [self.tabHeadView addSubview:footBtn];
    [footBtn setImgRightTitltLeft:10];
    footBtn.backgroundColor =  kButtonDefaultColor;
    footBtn.layer.cornerRadius = DimensionBaseIphone6(24);
    footBtn.layer.masksToBounds = YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat offset_Y = scrollView.contentOffset.y;
    
    if (offset_Y < 0) {
        if (offset_Y < - kNavigationBarHeight) {
            self.isOffsetY = YES;
        }
    }
    else{
        if (self.isOffsetY) {
            self.isOffsetY = NO;
            [self loadData];
        }
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/



#pragma mark ------goIdCardVertify------
- (void)goIdCardVertify:(NSString *)titleStr{
    [BoxLoadingHelper showBoxLoadingWithMessage:@""];
    NSMutableDictionary *muDic = @{
        @"largely":esString(self.idStr),
        @"enabled":@"enabledIdCard"
    }.mutableCopy;
    [HttpNetHelper getNetworkHelperForPath:kGetIdCardInfoUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        [BoxLoadingHelper hideBoxLoading];
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
            return;
        }
        
        NSDictionary *dic = responseDic[@"clip"];
        
        IdCardVertifyModel *model = [IdCardVertifyModel mj_objectWithKeyValues:dic];
        
        
        if ([model.ego.keller integerValue] == 0) {
            IdCardViewController *vc = [[IdCardViewController alloc] init];
            vc.idStr = esString(self.idStr);
            vc.orderNoStr = esString(self.model.refugees.passages);
            vc.title = esString(titleStr);
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        else if ([model.immunity.keller integerValue] == 0 ){
            IdCardFaceViewController *vc = [[IdCardFaceViewController alloc] init];
            vc.idStr = esString(self.idStr);
            vc.orderNoStr = esString(self.model.refugees.passages);
            vc.title = esString(titleStr);
            [self.navigationController pushViewController:vc animated:YES];
        }
        else{
            IdCardSuccessViewController *vc = [[IdCardSuccessViewController alloc] init];
            vc.nameStr = esString(model.ego.pureness.hydrogen);
            vc.idNoStr = esString(model.ego.pureness.shyly);
            vc.birDateStr = esString(model.ego.pureness.flattered);
            vc.idStr = esString(self.idStr);
            vc.orderNoStr = esString(self.model.refugees.passages);
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        
        
    } onCompleteFailur:^(NSError * _Nonnull error) {
        [BoxLoadingHelper hideBoxLoading];
    } withIsForm:NO];
    
}

#pragma mark ------goPersonalInfoVertify------
- (void)goPersonalInfoVertify:(NSString *)titleStr{
    PersonInfoViewController *vc = [[PersonInfoViewController alloc] init];
    vc.idStr = esString(self.idStr);
    vc.orderNoStr = esString(self.model.refugees.passages);
    vc.title = esString(titleStr);
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark ------goEmergencyInfoVertify------
- (void)goEmergencyInfoVertify:(NSString *)titleStr{
    ContactInfoViewController *vc = [[ContactInfoViewController alloc] init];
    vc.idStr = esString(self.idStr);
    vc.orderNoStr = esString(self.model.refugees.passages);
    vc.title = esString(titleStr);
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark ------goBankCardVertify------
- (void)goBankCardVertify:(NSString *)titleStr{
    BankCardInfoViewController *vc = [[BankCardInfoViewController alloc] init];
    vc.idStr = esString(self.idStr);
    vc.orderNoStr = esString(self.model.refugees.passages);
    vc.title = esString(titleStr);
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark ----clickStartBorrowing---
- (void)clickStartBorrowing{
    
    if (PMObjectIsEmpty(self.model.swears) || PMStringIsEmpty(self.model.swears.undiluted)) {

        self.startTimeStr = [NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"];
        
        NSMutableDictionary *muDic = @{
            @"dosed":esString(self.model.refugees.passages),
            @"founders":esString(self.model.refugees.founders),
            @"weakness":esString(self.model.refugees.weakness),
            @"shouldered":esString(self.model.refugees.shouldered),
            @"guiding":@"guidingIdStr",
            @"excuse":@"excuseIdStr",
        }.mutableCopy;
        self.startTimeStr = [NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"];
        [BoxLoadingHelper showBoxLoadingWithMessage:@""];
        [HttpNetHelper postNetworkHelperForPath:kOrderNoUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
            [BoxLoadingHelper hideBoxLoading];
            if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
                [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
                return;
            }
            self.endTimeStr = esString([NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"]);
            [self uploadMaiDianSDStartData];
            
            NSDictionary *dic = responseDic[@"clip"];
            
            [[DKCore sharedDKCore] jumpToControllerWithUrlString:esString(dic[@"twentieth"])];
          
        } onCompleteFailur:^(NSError * _Nonnull error) {
            [BoxLoadingHelper hideBoxLoading];
        } withIsForm:YES];
        
        return;
    }
    
    if ([self.model.swears.undiluted isEqualToString:kIdCardInfoVertify]) {
        [self goIdCardVertify:esString(self.model.swears.arrow)];
    }
    else if ([self.model.swears.undiluted isEqualToString:kPersonInfoVertify]) {
        [self goPersonalInfoVertify:esString(self.model.swears.arrow)];
    }
    else if ([self.model.swears.undiluted isEqualToString:kContactInfoVertify]) {
        [self goEmergencyInfoVertify:esString(self.model.swears.arrow)];
    }
    else if ([self.model.swears.undiluted isEqualToString:kBankInfoVertify]) {
        [self goBankCardVertify:esString(self.model.swears.arrow)];
    }
  
    
}



#pragma mark ----- uploadMaiDianSDStartData -------
- (void)uploadMaiDianSDStartData{
    self.timeInt = 0;
    self.isLocationSuccess = NO;
    [self initLocation];
}

- (void)initLocation{
    self.timer = [NSTimer timerWithTimeInterval:1.f target:self selector:@selector(addTimer) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 100;
    [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager requestLocation];
}

- (void)addTimer{
    self.timeInt ++;
    if (self.isLocationSuccess) {
        [self.timer invalidate];
        self.timer = nil;
        self.timeInt = 0;
    }
    else{
        if (self.timeInt > 8) {
            [self.timer invalidate];
            self.timer = nil;
            self.timeInt = 0;
            NSString *longitudeStr = [[NSUserDefaults standardUserDefaults] objectForKey:kStoreLongitude];
            NSString *latitudeStr = [[NSUserDefaults standardUserDefaults] objectForKey:kStoreLatitude];
            
            [self goServerWithLongitudeStr:PMStringIsEmpty(longitudeStr) ? @"" : longitudeStr withLatitudeStr:PMStringIsEmpty(latitudeStr) ? @"" : latitudeStr];
            
        }
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    
    CLLocation *newlocation = locations[0];
    NSString *longitudeStr = [NSString stringWithFormat:@"%lf",newlocation.coordinate.longitude];
    NSString *latitudeStr =  [NSString stringWithFormat:@"%lf",newlocation.coordinate.latitude];
    [self.locationManager stopUpdatingLocation];
    
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kStoreLongitude];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kStoreLatitude];
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lf",newlocation.coordinate.longitude] forKey:kStoreLongitude];
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lf",newlocation.coordinate.latitude] forKey:kStoreLatitude];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    self.isLocationSuccess = YES;
    
    if (self.timeInt <= 8) {
        [self goServerWithLongitudeStr:esString(longitudeStr) withLatitudeStr:esString(latitudeStr)];
    }

}

- (void)goServerWithLongitudeStr:(NSString *)longitudeStr withLatitudeStr:(NSString *)latitudeStr{
    [DataCategoryUpload uploadMaiDianData:@"8" withOrderIdStr:self.idStr withOrderNoStr:esString(self.model.refugees.passages) withLongitude:esString(longitudeStr) withLatitude:esString(latitudeStr) withStartTime:self.startTimeStr withEndTime:self.endTimeStr];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
}

@end
